/*
 * Copyright (c) $today.year-Now http://www.zxpnet.com All rights reserved.
 */

package com.zxp.common.core.security.authentication.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxp.common.api.R;
import com.zxp.common.core.security.properties.SecurityProperties;
import com.zxp.common.core.validatecode.ValidateCodeProperties;
import com.zxp.common.utils.WebUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: shollin
 * @date: 2021/7/6/006 8:17
 */
@RequiredArgsConstructor
@Slf4j
public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    private final ObjectMapper objectMapper;
    private final SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        log.info("MyAuthenticationFailHandler处理认证失败！");

        if (WebUtil.isAjaxRequest(request)) {
            WebUtil.renderJson(response, R.fail(exception.getMessage()));
        } else {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            // 判断是否有自定义错误页面,有则失败跳转到自定义页面。
            HttpSession session = request.getSession();
            // 将异常信息存到session对象里，若前后不分离的话，则可以从中取出异常信息展示到页面上。
            // 若前后分离，建议采取JSON的方式。
            session.setAttribute("msg", exception.getMessage());
            // 过期时间： 单位秒
            session.setMaxInactiveInterval(1);

            response.sendRedirect("/login?error");

            //super.onAuthenticationFailure(request, response, exception);
        }
    }
}
